package com.pinyougou.sellergoods.service.impl;

import java.util.List;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pinyougou.mapper.TbBrandMapper;

import com.pinyougou.pojo.TbBrandExample;
import entity.PageResult;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.pinyougou.pojo.TbBrand;
import com.pinyougou.sellergoods.service.BrandService;


@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private TbBrandMapper brandMapper;

    @Override
    /* 查询所有品牌*/
    public List<TbBrand> findAll() {

        return brandMapper.selectByExample(null);
    }

    @Override
    /* 查询所有品牌  （分页）*/
    public PageResult findPage(int pageNum, int pageSize) {

        PageHelper.startPage(pageNum,pageSize);

        Page<TbBrand> page = (Page<TbBrand>) brandMapper.selectByExample(null);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    /* 新增分类*/
    public Result add(TbBrand brand) {
        //判断是否重名
        TbBrandExample brandExample = new TbBrandExample();
        brandExample.createCriteria().andNameEqualTo(brand.getName());
        List<TbBrand> tbBrands = brandMapper.selectByExample(brandExample);
        if(tbBrands == null || tbBrands.size() == 0){
            brandMapper.insert(brand);
            return new Result(true,"添加成功",brand);
        }else {
            return new Result(false,"名称已存在");
        }
    }

    @Override
    /* 查询类别*/
    public TbBrand findOne(Long id) {
        if (id != null){
            TbBrand tbBrand = brandMapper.selectByPrimaryKey(id);
            if (tbBrand != null){
                return tbBrand;
            }
        }
        return null;
    }

    @Override
    /* 修改类别*/
    public void update(TbBrand brand) {

        brandMapper.updateByPrimaryKey(brand);

    }

    @Override
    /* 删除类别*/
    public void delete(Long[] ids) {
        if (ids != null && ids.length != 0){
            for (int i = 0;i<ids.length;i++){
                brandMapper.deleteByPrimaryKey(ids[i]);
            }
        }
    }

    @Override
    /* 站内搜索  （分页）*/
    public PageResult findPage(TbBrand tbBrand, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        TbBrandExample brandExample = new TbBrandExample();
        if (tbBrand != null){
            if(!StringUtils.isEmpty(tbBrand.getName())){
                brandExample.createCriteria().andNameLike("%"+tbBrand.getName()+"%");
            }
            if(!StringUtils.isEmpty(tbBrand.getFirstChar())){
                brandExample.createCriteria().andFirstCharLike("%"+tbBrand.getFirstChar()+"%");
            }
        }

        Page<TbBrand> page = (Page<TbBrand>) brandMapper.selectByExample(brandExample);

        return new PageResult(page.getTotal(),page.getResult());
    }


}

